package com.lanou3g.code0413.stream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * If there are no bugs, it was created by Chen FengYao on 2018/4/13;
 * Otherwise, I don't know who created it either
 */

public class Test03 {
    public static void main(String[] args) {
        File file = new File("out.txt");

        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);
            // 创建一个数组,从文件中读取的内容
            // 就放到这个数组中
            // 数组大小没有任何要求
            // 通常 都是1024(1KB) 或者 10*1024(10KB)
            byte[] buf = new byte[3];
            int num = 0;
            StringBuilder sb = new StringBuilder();
            while ((num = fis.read(buf)) != -1) {
                // 从字节数组 生成一个字符串
                System.out.println("num:" + num);
                String data = new String(buf, 0, num);
                System.out.println("这一次读到了:"+data);
                sb.append(data);
            }
            // 拿到最后的数据
            String result = sb.toString();
            System.out.println(result);

            List<User> users = getUsers(result);
            for (User user : users) {
                System.out.println(user.getUsername());
            }



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    private static List<User> getUsers(String data){
        List<User> users = new ArrayList<>();
        String[] userInfos = data.split(";");
        for (String userInfo : userInfos) {
            // userInfo => aa12345:Aa123456
            System.out.println(userInfo);
            String[] info = userInfo.split(":");
            if (info.length == 2) {
                User user = new User();
                user.setUsername(info[0]);
                user.setPsd(info[1]);
                users.add(user);
            }
        }
        return users;
    }
}
